#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>


void *pthr_fun1(void *arg);
void *pthr_fun3(void *arg);
void *pthr_fun2(void *arg);
void cleanup(void *arg);

int main(int argc, char **argv)
{
	int			rv = -1;
	pthread_t	tid1,tid2,tid3;
	
	rv = pthread_create(&tid1,NULL,pthr_fun1,(void *)1);
	if(rv != 0)
	{
		printf("create 1 error\n");
		return -1;
	}
	
	printf("pthread 1 succed\n");

	rv = pthread_create(&tid2,NULL,pthr_fun2,(void *)1);
	if(rv != 0)
	{
		printf("create 2 error\n");
		return -2;
	}

	printf("pthread 1 succed\n");

	rv = pthread_join(tid1,NULL);
	if(rv != 0)
	{
		printf("join error 1 \n");
	}


	rv = pthread_create(&tid3,NULL,pthr_fun3,(void *)1);
	if(rv != 0)
	{
		printf("create 3 error\n");
		return -3;
	}

	printf("pthread 3 succed\n");
	
	printf(" pthread 1 exit\n");

	rv = pthread_join(tid2,NULL);
	if(rv != 0)
	{
		printf("join error 2 \n");
	}

	rv = pthread_join(tid3,NULL);
	if(rv != 0)
	{
		printf("join error 3 \n");
	}

	printf(" pthread 3 exit\n");

	return 0;
}


void cleanup(void *arg)
{
	printf("cleanup :%s \n",(char *)arg);
}


void *pthr_fun1(void *arg)
{
	printf(" pthread 1 start \n");

	pthread_cleanup_push(cleanup, "thread 1 : 11");
	pthread_cleanup_push(cleanup, "thread 1 : 22");

	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);

	printf("pthread exit 1 \n");
	pthread_exit(0);
}

void *pthr_fun2(void *arg)
{
	printf(" pthread 2 start \n");

	pthread_cleanup_push(cleanup, "thread 2 : 11");
	pthread_cleanup_push(cleanup, "thread 2 : 22");

	pthread_cleanup_pop(1);
	pthread_cleanup_pop(1);

	printf("pthread exit 2 \n");

	pthread_exit(0);
}


void *pthr_fun3(void *arg)
{
	printf(" pthread 3 start \n");

	pthread_cleanup_push(cleanup, "thread 3 : 11");
	pthread_cleanup_push(cleanup, "thread 3 : 22");

	printf("pthread exit 3 \n");
	pthread_exit((void *)1);

	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);

}

